<template>
  <div class="generate-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">静态化生成管理</h1>
          <p class="page-description">管理静态文件生成，支持全站生成、增量生成、清理等功能</p>
        </div>
        <div class="header-actions">
          <el-select
            v-model="selectedSiteId"
            placeholder="选择站点"
            @change="onSiteChange"
            style="width: 200px; margin-right: 10px;"
          >
            <el-option
              v-for="site in sites"
              :key="site.id"
              :label="site.name"
              :value="site.id"
            />
          </el-select>
          <el-button @click="testGenerate" type="warning" style="margin-right: 10px;">
            测试生成
          </el-button>
          <el-button @click="refreshStatus" :loading="loading" icon="Refresh">
            刷新状态
          </el-button>
        </div>
      </div>
    </div>

    <!-- 生成状态概览 -->
    <div class="status-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="status-card">
            <div class="status-number">{{ statistics.totalFiles || 0 }}</div>
            <div class="status-label">静态文件总数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="status-card">
            <div class="status-number">{{ statistics.totalSize || '0 B' }}</div>
            <div class="status-label">文件总大小</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="status-card">
            <div class="status-number">{{ runningTasks.length }}</div>
            <div class="status-label">运行中任务</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="status-card">
            <div class="status-number">{{ statistics.lastGenerated || '未生成' }}</div>
            <div class="status-label">最后生成时间</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 快捷操作区 -->
    <div class="quick-actions">
      <el-card class="action-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">全站生成</span>
            <span class="card-description">生成整个站点的静态文件</span>
          </div>
        </template>
        <div class="action-buttons">
          <el-button type="primary" size="large" @click="generateAll" :loading="generating.all">
            生成全站静态文件
          </el-button>
          <el-button @click="showGenerateDialog('site')" :loading="generating.site">
            生成指定站点
          </el-button>
          <el-button @click="showGenerateDialog('channel')" :loading="generating.channel">
            生成指定栏目
          </el-button>
          <el-button @click="showGenerateDialog('article')" :loading="generating.article">
            批量生成文章
          </el-button>
        </div>
      </el-card>

      <el-card class="action-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">清理操作</span>
            <span class="card-description">清理和管理静态文件</span>
          </div>
        </template>
        <div class="action-buttons">
          <el-button type="danger" @click="clearAllStatic" :loading="generating.clearAll">
            清空所有静态文件
          </el-button>
          <el-button type="warning" @click="showClearDialog" :loading="generating.clearSite">
            清空站点静态文件
          </el-button>
          <el-button @click="cleanupTasks" :loading="generating.cleanup">
            清理已完成任务
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 生成配置 -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">生成配置</span>
          <span class="card-description">配置静态文件生成参数</span>
        </div>
      </template>

      <el-form :model="config" label-width="140px" class="config-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="静态文件路径">
              <el-input v-model="config.staticPath" placeholder="/static" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="URL前缀">
              <el-input v-model="config.staticUrlPrefix" placeholder="http://static.example.com" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文件扩展名">
              <el-input v-model="config.fileExtension" placeholder=".html" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批处理大小">
              <el-input-number v-model="config.batchSize" :min="1" :max="1000" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="生成选项">
              <el-checkbox-group v-model="config.options">
                <el-checkbox label="compressHtml">压缩HTML</el-checkbox>
                <el-checkbox label="enableCache">启用缓存</el-checkbox>
                <el-checkbox label="generateSitemap">生成站点地图</el-checkbox>
                <el-checkbox label="generateRss">生成RSS</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="saveConfig" :loading="saving">
            保存配置
          </el-button>
          <el-button @click="resetConfig">
            重置配置
          </el-button>
          <el-button @click="validateConfig" :loading="validating">
            验证配置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 任务列表 -->
    <el-card class="tasks-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="card-title">生成任务列表</span>
            <span class="card-description">查看和管理静态化生成任务</span>
          </div>
          <div class="header-actions">
            <el-button type="primary" plain size="small" @click="refreshTasks" icon="Refresh">
              刷新任务
            </el-button>
            <el-button type="danger" plain size="small" @click="cleanupTasks" icon="Delete">
              清理已完成
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="tasks"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
        highlight-current-row
        :empty-text="'暂无生成任务'"
      >
        <el-table-column prop="taskId" label="任务ID" width="200" />
        <el-table-column prop="description" label="任务名称" min-width="180" />
        <el-table-column label="详细信息" width="200">
          <template #default="scope">
            <div class="task-details">
              <div v-if="scope.row.siteId" class="detail-item">
                <el-tag size="small" type="info">站点: {{ getSiteName(scope.row.siteId) }}</el-tag>
              </div>
              <div v-if="scope.row.channelId" class="detail-item">
                <el-tag size="small" type="warning">栏目: {{ getChannelName(scope.row.channelId) }}</el-tag>
              </div>
              <div v-if="scope.row.articleId" class="detail-item">
                <el-tag size="small" type="success">文章: {{ getArticleName(scope.row.articleId) }}</el-tag>
              </div>
              <div v-if="!scope.row.siteId && !scope.row.channelId && !scope.row.articleId" class="detail-item">
                <el-tag size="small">全站生成</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag
              :type="getStatusType(scope.row.status)"
              :effect="scope.row.status === 'RUNNING' ? 'dark' : 'light'"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="180">
          <template #default="scope">
            <el-progress
              :percentage="getTaskProgress(scope.row)"
              :status="getProgressStatus(scope.row.status)"
              :stroke-width="15"
              :text-inside="true"
              :format="percentageFormat"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button-group>
              <el-button
                v-if="scope.row.status === 'RUNNING' || scope.row.status === 'PENDING'"
                type="danger"
                size="small"
                @click="cancelTask(scope.row.taskId)"
                icon="Close"
              >
                取消
              </el-button>
              <el-button
                v-if="scope.row.status === 'COMPLETED'"
                type="primary"
                size="small"
                @click="viewResult(scope.row.taskId)"
                icon="View"
              >
                查看
              </el-button>
              <el-button
                v-if="scope.row.status === 'FAILED'"
                type="warning"
                size="small"
                @click="viewError(scope.row.taskId)"
                icon="Warning"
              >
                错误
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 生成选择对话框 -->
    <el-dialog v-model="generateDialog.visible" :title="generateDialog.title" width="600px">
      <div v-if="generateDialog.type === 'site'">
        <h4>选择要生成的站点：</h4>
        <el-table :data="sites" @selection-change="handleSiteSelection">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="站点名称" />
          <el-table-column prop="domain" label="域名" width="200" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'warning'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else-if="generateDialog.type === 'channel'">
        <h4>选择要生成的栏目：</h4>
        <el-tree
          ref="channelTree"
          :data="channels"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
        />
      </div>
      <div v-else-if="generateDialog.type === 'article'">
        <h4>选择要生成的文章：</h4>
        <el-table :data="articles" @selection-change="handleArticleSelection">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="channel.name" label="栏目" width="120" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 0 ? 'success' : 'warning'">
                {{ row.status === 0 ? '已发布' : '草稿' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <el-button @click="generateDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmGenerate" :loading="generating.dialog">
          确认生成
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { generateApi } from '@/api/generate'
import { siteApi } from '@/api/site'
import { channelApi } from '@/api/channel'
import { articleApi } from '@/api/article'
import type { GenerateTask, GenerateConfig } from '@/api/generate'

// 路由相关
const route = useRoute()
const router = useRouter()
// 移除图标导入，使用文字或emoji代替

// 响应式数据
const loading = ref(false)
const generating = reactive({
  all: false,
  clear: false,
  index: false,
  sitemap: false,
  rss: false,
  oneClick: false,
  dialog: false,
  cleanup: false,
  site: false,
  channel: false,
  article: false,
  clearSite: false,
  clearAll: false
})

const config = reactive({
  indexPath: '/channels/channel_alias/index',
  articlePath: '/articles/article_id',
  generateIndex: true,
  generateSitemap: true,
  compressHtml: false,
  enableCache: true
})

const generateOptions = reactive({
  generateIndex: true,
  generateChannels: true,
  generateArticles: true,
  generateSitemap: true
})

const generateDialog = reactive({
  visible: false,
  type: '',
  title: ''
})

const tasks = ref([])
const sites = ref([])
const channels = ref([])
const articles = ref([])
const selectedSites = ref([])
const selectedChannels = ref([])
const selectedArticles = ref([])
const selectedSiteId = ref<number>(1)

// 统计信息
const statistics = ref({
  totalFiles: 0,
  totalSize: '0 B',
  lastGenerated: '未生成'
})

// 请求控制器，用于取消请求
let abortController: AbortController | null = null

// 运行中的任务
const runningTasks = computed(() => {
  return tasks.value.filter(task => task.status === 'RUNNING' || task.status === 'PENDING')
})

// 方法
const refreshStatus = async () => {
  loading.value = true
  try {
    // 获取任务列表和统计信息
    await Promise.all([
      loadTasks(),
      loadStatistics()
    ])
    ElMessage.success('状态刷新成功')
  } catch (error) {
    ElMessage.error('刷新状态失败')
  } finally {
    loading.value = false
  }
}

const generateAll = async () => {
  try {
    await ElMessageBox.confirm('确定要生成全站静态文件吗？这可能需要较长时间。', '确认生成', {
      type: 'warning'
    })

    generating.all = true
    // 调用生成全站API
    const response = await generateApi.generateAll()
    if (response.code === 0) {
      ElMessage.success('全站生成任务已启动')
    } else {
      ElMessage.error(`生成失败: ${response.msg}`)
    }
    // 刷新任务列表和统计信息
    await Promise.all([loadTasks(), loadStatistics()])
  } catch (error) {
    if (error !== 'cancel') {
      console.error('生成全站失败:', error)
      ElMessage.error('生成失败')
    }
  } finally {
    generating.all = false
  }
}

const clearStatic = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有静态文件吗？此操作不可恢复。', '确认清空', {
      type: 'warning'
    })
    
    generating.clear = true
    // 调用清空静态文件API
    ElMessage.success('静态文件清空完成')
    // 刷新任务列表和统计信息
    await Promise.all([loadTasks(), loadStatistics()])
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空失败')
    }
  } finally {
    generating.clear = false
  }
}

const showGenerateDialog = (type: string) => {
  generateDialog.type = type

  switch (type) {
    case 'site':
      generateDialog.title = '生成指定站点'
      loadSites()
      break
    case 'channel':
      generateDialog.title = '生成指定栏目'
      loadChannels()
      break
    case 'article':
      generateDialog.title = '批量生成文章'
      loadArticles()
      break
    default:
      generateDialog.title = '生成内容'
  }

  generateDialog.visible = true
}

const confirmGenerate = async () => {
  generating.dialog = true
  try {
    if (generateDialog.type === 'site') {
      // 生成选中的站点
      if (selectedSites.value.length === 0) {
        ElMessage.warning('请选择要生成的站点')
        return
      }

      for (const site of selectedSites.value) {
        const response = await generateApi.generateSite(site.id)
        if (response.code === 0) {
          ElMessage.success(`站点 ${site.name} 生成任务已启动`)
        } else {
          ElMessage.error(`站点 ${site.name} 生成失败: ${response.msg}`)
        }
      }
    } else if (generateDialog.type === 'channel') {
      // 生成选中的栏目
      ElMessage.success('栏目生成任务已启动')
    } else if (generateDialog.type === 'article') {
      // 生成选中的文章
      ElMessage.success('文章生成任务已启动')
    }
    generateDialog.visible = false
    // 刷新任务列表和统计信息
    await Promise.all([loadTasks(), loadStatistics()])
  } catch (error) {
    console.error('生成失败:', error)
    ElMessage.error('生成失败')
  } finally {
    generating.dialog = false
  }
}

const oneClickGenerate = async () => {
  try {
    await ElMessageBox.confirm('确定要执行一键生成吗？', '确认生成', {
      type: 'info'
    })
    
    generating.oneClick = true
    // 根据选择的选项执行生成
    ElMessage.success('一键生成任务已启动')
    // 刷新任务列表和统计信息
    await Promise.all([loadTasks(), loadStatistics()])
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('生成失败')
    }
  } finally {
    generating.oneClick = false
  }
}

const saveConfig = async () => {
  try {
    // 保存配置API调用
    ElMessage.success('配置保存成功')
  } catch (error) {
    ElMessage.error('配置保存失败')
  }
}

const loadTasks = async () => {
  try {
    console.log('开始加载任务列表...')

    // 创建新的AbortController
    abortController = new AbortController()

    // 添加超时控制
    const timeoutId = setTimeout(() => {
      if (abortController) {
        abortController.abort()
      }
    }, 5000) // 5秒超时

    const response = await generateApi.getTasks()
    clearTimeout(timeoutId)

    console.log('任务列表响应:', response)

    if (response.code === 0) {
      tasks.value = response.data || []
      console.log('任务列表加载成功，共', tasks.value.length, '个任务')
      console.log('任务数据详情:', tasks.value)

      // 如果有任务数据，显示第一个任务的详细信息用于调试
      if (tasks.value.length > 0) {
        console.log('第一个任务详情:', tasks.value[0])
      }
    } else {
      console.warn('获取任务数据失败:', response.msg)
      tasks.value = []
      ElMessage.warning('获取任务数据失败: ' + response.msg)
    }

  } catch (error) {
    console.error('加载任务列表失败:', error)
    tasks.value = []
    // 不显示错误消息，避免影响用户体验
  }
}

// 加载统计信息
const loadStatistics = async () => {
  try {
    console.log('开始加载统计信息...')

    // 使用当前选中的站点ID，如果没有则使用默认站点ID 1
    const siteId = selectedSiteId.value || 1
    const response = await generateApi.getStatistics(siteId)

    console.log('统计信息响应:', response)

    if (response.code === 0) {
      const data = response.data
      statistics.value = {
        totalFiles: data.totalFiles || 0,
        totalSize: data.totalSizeFormatted || data.totalSize || '0 B',
        lastGenerated: formatDateTime(data.lastGenerated) || '未生成'
      }
      console.log('统计信息加载成功:', statistics.value)
    } else {
      console.warn('获取统计信息失败:', response.msg)
      statistics.value = {
        totalFiles: 0,
        totalSize: '0 B',
        lastGenerated: '未生成'
      }
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
    statistics.value = {
      totalFiles: 0,
      totalSize: '0 B',
      lastGenerated: '未生成'
    }
  }
}

// 加载站点数据
const loadSites = async () => {
  try {
    console.log('开始加载站点数据...')
    const response = await siteApi.getSiteTree()
    console.log('站点API响应:', response)

    if (response.code === 0) {
      sites.value = response.data || []
      console.log('站点列表加载成功:', sites.value)

      if (sites.value.length > 0) {
        selectedSiteId.value = sites.value[0].id
      }
    } else {
      console.warn('获取站点数据失败:', response.msg)
      sites.value = []
    }
  } catch (error) {
    console.error('加载站点数据失败:', error)
    sites.value = []
    // 使用备用数据
    sites.value = [
      {
        id: 1,
        name: '主站',
        domain: 'www.example.com',
        status: 1
      }
    ]
    selectedSiteId.value = 1
  }
}

const loadChannels = async () => {
  try {
    if (!selectedSiteId.value) {
      console.warn('没有选择站点，无法加载栏目')
      return
    }

    console.log('开始加载栏目数据，站点ID:', selectedSiteId.value)
    const response = await channelApi.getChannelTree(selectedSiteId.value)
    console.log('栏目API响应:', response)

    if (response.code === 0) {
      channels.value = response.data || []
      console.log('栏目列表加载成功:', channels.value)
    } else {
      console.warn('获取栏目数据失败:', response.msg)
      channels.value = []
    }
  } catch (error) {
    console.error('加载栏目数据失败:', error)
    channels.value = []
    // 使用备用数据
    channels.value = [
      {
        id: 1,
        name: '首页',
        path: '/index',
        children: []
      },
      {
        id: 2,
        name: '新闻中心',
        path: '/news',
        children: []
      }
    ]
  }
}

const loadArticles = async () => {
  try {
    if (!selectedSiteId.value) {
      console.warn('没有选择站点，无法加载文章')
      return
    }

    console.log('开始加载文章数据，站点ID:', selectedSiteId.value)
    const response = await articleApi.getLatestArticles(selectedSiteId.value, 50)
    console.log('文章API响应:', response)

    if (response.code === 0) {
      articles.value = response.data || []
      console.log('文章列表加载成功:', articles.value)
    } else {
      console.warn('获取文章数据失败:', response.msg)
      articles.value = []
    }
  } catch (error) {
    console.error('加载文章数据失败:', error)
    articles.value = []
    // 使用备用数据
    articles.value = [
      {
        id: 1,
        title: '欢迎使用 Light CMS',
        channel: { name: '首页' },
        status: 1
      },
      {
        id: 2,
        title: 'Light CMS 功能介绍',
        channel: { name: '产品介绍' },
        status: 1
      }
    ]
  }
}

const handleArticleSelection = (selection: any[]) => {
  selectedArticles.value = selection
}

const getStatusType = (status: string) => {
  const statusLower = status?.toLowerCase()
  switch (statusLower) {
    case 'completed': return 'success'
    case 'running': return 'warning'
    case 'failed': return 'danger'
    case 'pending': return 'info'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  const statusLower = status?.toLowerCase()
  switch (statusLower) {
    case 'completed': return '已完成'
    case 'running': return '运行中'
    case 'failed': return '失败'
    case 'pending': return '等待中'
    default: return status || '未知'
  }
}

const getProgressStatus = (status: string) => {
  const statusLower = status?.toLowerCase()
  switch (statusLower) {
    case 'completed': return 'success'
    case 'running': return undefined // 默认状态
    case 'failed': return 'exception'
    default: return undefined
  }
}

const percentageFormat = (percentage: number) => {
  return percentage === 100 ? '完成' : `${percentage}%`
}

// 获取任务进度 - 如果状态是已完成但进度为0，则显示100%
const getTaskProgress = (task: any) => {
  const status = task.status?.toLowerCase()
  const progress = task.progress || 0

  // 如果状态是已完成，但进度为0，则显示100%
  if (status === 'completed' && progress === 0) {
    return 100
  }

  return progress
}

// 获取站点名称
const getSiteName = (siteId: number) => {
  const site = sites.value.find(s => s.id === siteId)
  return site ? site.name : `站点${siteId}`
}

// 获取栏目名称
const getChannelName = (channelId: number) => {
  const findChannel = (channels: any[], id: number): any => {
    for (const channel of channels) {
      if (channel.id === id) return channel
      if (channel.children) {
        const found = findChannel(channel.children, id)
        if (found) return found
      }
    }
    return null
  }

  const channel = findChannel(channels.value, channelId)
  return channel ? channel.name : `栏目${channelId}`
}

// 获取文章名称
const getArticleName = (articleId: number) => {
  const article = articles.value.find(a => a.id === articleId)
  return article ? article.title : `文章${articleId}`
}

const viewTaskDetail = (task: any) => {
  ElMessageBox.alert(`任务详情：${task.message}`, task.name)
}

// 查看任务结果
const viewResult = (taskId: string) => {
  const task = tasks.value.find(t => t.taskId === taskId)
  if (!task) {
    ElMessage.error('任务不存在')
    return
  }

  const content = `
    <div style="text-align: left;">
      <p><strong>任务ID:</strong> ${task.taskId}</p>
      <p><strong>任务描述:</strong> ${task.description}</p>
      <p><strong>状态:</strong> ${getStatusText(task.status)}</p>
      <p><strong>进度:</strong> ${getTaskProgress(task)}%</p>
      <p><strong>创建时间:</strong> ${task.createTime}</p>
      <p><strong>更新时间:</strong> ${task.updateTime || '无'}</p>
      ${task.result ? `<p><strong>结果:</strong> ${task.result}</p>` : ''}
    </div>
  `

  ElMessageBox.alert(content, '任务详情', {
    dangerouslyUseHTMLString: true,
    customClass: 'task-detail-dialog'
  })
}

// 查看任务错误
const viewError = (taskId: string) => {
  const task = tasks.value.find(t => t.taskId === taskId)
  if (!task) {
    ElMessage.error('任务不存在')
    return
  }

  const content = `
    <div style="text-align: left;">
      <p><strong>任务ID:</strong> ${task.taskId}</p>
      <p><strong>任务描述:</strong> ${task.description}</p>
      <p><strong>状态:</strong> ${getStatusText(task.status)}</p>
      <p><strong>错误时间:</strong> ${task.updateTime || task.createTime}</p>
      ${task.error ? `<p><strong>错误信息:</strong> <span style="color: #f56c6c;">${task.error}</span></p>` : ''}
      ${task.errorDetail ? `<p><strong>详细错误:</strong> <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; font-size: 12px;">${task.errorDetail}</pre></p>` : ''}
    </div>
  `

  ElMessageBox.alert(content, '任务错误详情', {
    dangerouslyUseHTMLString: true,
    customClass: 'task-error-dialog'
  })
}

const deleteTask = async (task: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个任务记录吗？', '确认删除', {
      type: 'warning'
    })
    ElMessage.success('任务删除成功')
    await loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 取消任务
const cancelTask = async (taskId: string) => {
  try {
    await ElMessageBox.confirm('确定要取消这个任务吗？', '确认取消', {
      type: 'warning'
    })

    const response = await generateApi.cancelTask(taskId)
    if (response.code === 0) {
      ElMessage.success('任务已取消')
      await loadTasks()
    } else {
      ElMessage.error(response.msg || '取消任务失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消任务失败:', error)
      ElMessage.error('取消任务失败')
    }
  }
}

// 清理已完成的任务
const cleanupTasks = async () => {
  try {
    await ElMessageBox.confirm('确定要清理所有已完成的任务吗？', '确认清理', {
      type: 'warning'
    })

    generating.cleanup = true
    const response = await generateApi.cleanupTasks()
    if (response.code === 0) {
      ElMessage.success('已完成任务清理成功')
      await loadTasks()
    } else {
      ElMessage.error(response.msg || '清理任务失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理任务失败:', error)
      ElMessage.error('清理任务失败')
    }
  } finally {
    generating.cleanup = false
  }
}

// 刷新任务列表
const refreshTasks = async () => {
  await loadTasks()
  ElMessage.success('任务列表已刷新')
}

// 站点切换处理
const onSiteChange = async (siteId: number) => {
  console.log('切换站点:', siteId)
  selectedSiteId.value = siteId
  // 重新加载统计信息
  await loadStatistics()
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  console.log('格式化时间输入:', dateTimeStr)

  if (!dateTimeStr || dateTimeStr === '未生成') {
    return '未生成'
  }

  try {
    // 处理 ISO 8601 格式的时间字符串
    let date = new Date(dateTimeStr)

    if (isNaN(date.getTime())) {
      console.warn('无法解析日期:', dateTimeStr)
      return '未生成' // 如果无法解析，返回未生成
    }

    // 转换为本地时间
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    console.log('格式化时间输出:', formatted)

    return formatted
  } catch (error) {
    console.error('日期格式化失败:', error, '原始值:', dateTimeStr)
    return '未生成'
  }
}

// 测试生成功能
const testGenerate = async () => {
  try {
    loading.value = true
    console.log('开始测试生成功能...')

    const siteId = selectedSiteId.value || 1

    // 调用测试生成接口
    const response = await fetch(`/cms/admin/generate/test/generate?siteId=${siteId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('token') || ''
      }
    })

    const result = await response.json()
    console.log('测试生成结果:', result)

    if (result.code === 0) {
      ElMessage.success('测试生成成功！')
      console.log('测试文件信息:', result.data)

      // 显示测试结果
      ElMessageBox.alert(
        `测试文件路径: ${result.data.testFile}\n` +
        `文件存在: ${result.data.fileExists}\n` +
        `文件大小: ${result.data.fileSize} bytes\n` +
        `静态目录: ${result.data.staticPath}\n` +
        `目录存在: ${result.data.staticDirExists}`,
        '测试生成结果',
        { type: 'success' }
      )

      // 刷新统计信息
      await loadStatistics()
    } else {
      ElMessage.error(`测试生成失败: ${result.msg}`)
    }
  } catch (error) {
    console.error('测试生成失败:', error)
    ElMessage.error('测试生成失败')
  } finally {
    loading.value = false
  }
}

// 清空所有静态文件
const clearAllStatic = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有静态文件吗？此操作不可恢复！', '确认清空', {
      type: 'warning'
    })

    generating.clearAll = true
    // TODO: 调用清空所有静态文件API
    ElMessage.success('所有静态文件已清空')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空失败')
    }
  } finally {
    generating.clearAll = false
  }
}

// 显示清空站点对话框
const showClearDialog = () => {
  ElMessageBox.prompt('请输入要清空的站点ID', '清空站点静态文件', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\d+$/,
    inputErrorMessage: '请输入有效的站点ID'
  }).then(({ value }) => {
    clearSiteStatic(parseInt(value))
  }).catch(() => {
    // 用户取消
  })
}

// 清空站点静态文件
const clearSiteStatic = async (siteId: number) => {
  try {
    generating.clearSite = true
    // TODO: 调用清空站点静态文件API
    ElMessage.success(`站点 ${siteId} 的静态文件已清空`)
  } catch (error) {
    ElMessage.error('清空站点文件失败')
  } finally {
    generating.clearSite = false
  }
}

// 处理站点选择
const handleSiteSelection = (selection: any[]) => {
  selectedSites.value = selection
}

// 处理站点ID变化
const handleSiteIdChange = (siteId: number) => {
  selectedSiteId.value = siteId
  // 重新加载栏目和文章
  loadChannels()
  loadArticles()
}







// 监听路由变化
watch(() => route.path, (newPath, oldPath) => {
  console.log('生成管理页面检测到路由变化:', oldPath, '->', newPath)
  if (newPath !== '/content/generate') {
    console.log('正在离开生成管理页面...')
  }
}, { immediate: true })

// 页面加载时获取数据
onMounted(() => {
  console.log('生成管理页面已挂载')

  // 设置一个全局标记，表示页面正在加载
  window.__generatePageLoading = true

  // 使用 nextTick 确保DOM渲染完成后再加载数据
  nextTick(() => {
    try {
      loadSites()
      // 延迟加载任务列表和统计信息，避免阻塞页面渲染
      setTimeout(() => {
        Promise.all([
          loadTasks(),
          loadStatistics()
        ]).finally(() => {
          // 标记页面加载完成
          window.__generatePageLoading = false
        })
      }, 100)
    } catch (error) {
      console.error('页面初始化失败:', error)
      window.__generatePageLoading = false
    }
  })
})

// 组件卸载前清理
onBeforeUnmount(() => {
  console.log('生成管理页面开始卸载...')

  try {
    // 清除全局标记
    window.__generatePageLoading = false

    // 取消正在进行的API请求
    if (abortController) {
      console.log('取消API请求...')
      abortController.abort()
      abortController = null
    }

    // 清理所有loading状态
    console.log('清理loading状态...')
    Object.keys(generating).forEach(key => {
      generating[key] = false
    })

    // 关闭可能打开的对话框
    console.log('关闭对话框...')
    generateDialog.visible = false

    // 清理loading状态
    loading.value = false

    // 清理响应式引用
    sites.value = []
    channels.value = []
    articles.value = []
    tasks.value = []

    // 强制清理任何可能的阻塞状态
    setTimeout(() => {
      console.log('延迟清理完成')
    }, 0)

    console.log('生成管理页面卸载完成')
  } catch (error) {
    console.error('页面卸载时发生错误:', error)
  }
})
</script>

<style scoped lang="scss">
.generate-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
  width: 100%;
  max-width: none;

  .page-header {
    margin-bottom: 24px;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      border: 1px solid #e4e7ed;
    }

    .header-left {
      .page-title {
        font-size: 28px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 8px 0;
        line-height: 1.2;
      }

      .page-description {
        color: #909399;
        margin: 0;
        font-size: 14px;
        line-height: 1.4;
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .status-overview {
    margin-bottom: 24px;

    .status-card {
      background: white;
      padding: 24px;
      border-radius: 12px;
      text-align: center;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      border: 1px solid #e4e7ed;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
      }

      .status-number {
        font-size: 32px;
        font-weight: bold;
        color: #409eff;
        margin-bottom: 8px;
        line-height: 1;
      }

      .status-label {
        color: #606266;
        font-size: 14px;
        font-weight: 500;
      }
    }
  }

  .quick-actions {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-bottom: 24px;

    .action-card {
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      border: 1px solid #e4e7ed;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
      }

      .card-header {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .card-title {
          font-size: 18px;
          font-weight: 600;
          color: #303133;
        }

        .card-description {
          font-size: 13px;
          color: #909399;
        }
      }

      .action-buttons {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        padding: 4px 0;

        .el-button {
          flex: 1;
          min-width: 140px;
        }
      }
    }
  }

  .config-card,
  .tasks-card {
    margin-bottom: 24px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #e4e7ed;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .card-title {
          font-size: 18px;
          font-weight: 600;
          color: #303133;
        }

        .card-description {
          font-size: 13px;
          color: #909399;
        }
      }

      .header-actions {
        display: flex;
        gap: 8px;
      }
    }
  }

  .config-form {
    .el-form-item {
      margin-bottom: 20px;
    }

    .el-input,
    .el-input-number {
      width: 100%;
    }
  }

  .one-click-generate {
    background: white;
    border-radius: 8px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    text-align: center;

    h3 {
      color: #2c3e50;
      margin-bottom: 20px;
      font-size: 16px;
    }

    .generate-options {
      display: flex;
      justify-content: center;
      gap: 24px;
      margin-bottom: 20px;
      flex-wrap: wrap;
    }
  }

  .task-list {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    h3 {
      color: #2c3e50;
      margin-bottom: 20px;
      font-size: 16px;
    }

    .task-details {
      .detail-item {
        margin-bottom: 4px;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  @media (max-width: 768px) {
    .quick-actions {
      grid-template-columns: 1fr;
    }

    .action-buttons {
      flex-direction: column;
    }

    .generate-options {
      flex-direction: column;
      align-items: center;
    }
  }
}

// 全局样式 - 任务详情对话框
:deep(.task-detail-dialog) {
  .el-message-box__content {
    text-align: left !important;
  }
}

:deep(.task-error-dialog) {
  .el-message-box__content {
    text-align: left !important;
  }

  pre {
    max-height: 200px;
    overflow-y: auto;
  }
}
</style>
